#include "InetAddr.h"

#include <string.h>
#include <stdexcept>

InetAddr::InetAddr(const string &ip, unsigned int port)
{
    memset(&_addr, 0, sizeof(_addr));
    if (ip.empty())
    {
        throw std::invalid_argument("IP address cannot be empty");
    }
    _addr.sin_family = AF_INET;
    _addr.sin_port = htons(port);
    _addr.sin_addr.s_addr = inet_addr(ip.c_str());
}

InetAddr::InetAddr(const struct sockaddr_in &addr)
    : _addr(addr)
{
}

InetAddr::~InetAddr()
{
}
string InetAddr::ip() const
{
    return string(inet_ntoa(_addr.sin_addr));
}

unsigned int InetAddr::port() const
{
    return ntohs(_addr.sin_port); // 网络字节序 -> 主机字节序
}

const struct sockaddr *InetAddr::getAddrPtr() const
{
    return reinterpret_cast<const sockaddr*>(&_addr);
}

struct sockaddr_in *InetAddr::getAddrinPtr() 
{
    return &_addr;
}